<?php
/**
 * 腾讯云-短信
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2019/10/26
 * Time: 6:07 PM
 */
namespace Util\TencentCloud;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;

use Util\TencentCloud\CommonRequest;

class Sms
{
    /**
     * 腾讯云安全凭证
     * @var string $secret_id
     */
    private $secret_id;

    /**
     * 腾讯云安全凭证
     * @var string $secret_key
     */
    private $secret_key;

    private $apiUrl = 'https://sms.tencentcloudapi.com';

    private $SmsSdkAppid;

    private $Sign;

    public function __construct($secret_id='', $secret_key='', $SmsSdkAppid = '1400250992', $Sign = '源点计划')
    {
        $this->SmsSdkAppid = $SmsSdkAppid;
        $this->Sign = $Sign;
        $this->secret_id = $secret_id;
        $this->secret_key = $secret_key;
    }

    /**
     * 发送短信
     * 官网文档地址:https://cloud.tencent.com/document/api/382/38778
     * @param $templateId string 发送短信模板id
     * @param $mobile array 接受短信手机号
     * @param $templateParams array 短信内容参数
     */
    public function SendSms($templateId, $mobile, $templateParams)
    {
        $postData = [
            'PhoneNumberSet' => $mobile,
            'TemplateID'  => $templateId,
            'Sign'  => $this->Sign,
            'TemplateParamSet' => $templateParams,
            'SmsSdkAppid' => $this->SmsSdkAppid, // 短信应用的唯一标识
        ];

        $header = CommonRequest::createCommonRequestHeader('ap-chengdu', $this->secret_id, $this->secret_key, 'sms', $postData, 'sms.tencentcloudapi.com', 'sms');

        $curl_option = [
            CURLOPT_HTTPHEADER => [
                'Content-Type:application/json',
                'X-TC-Action:SendSms',
                'X-TC-Timestamp:'.$header['X-TC-Timestamp'],
                'X-TC-Version:2019-07-11',
                'X-TC-Region:'.$header['X-TC-Region'],
                'Authorization:'.$header['Authorization'],
            ],
        ];

        //V(json_encode($postData, JSON_UNESCAPED_UNICODE));
        $reponse = request($this->apiUrl, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true,   $curl_option);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['Response']['Error']) ){
                return ResultWrapper::fail($reponseData['Response']['Error']['Message'], ErrorCode::$apiNotResult);
            }
            return ResultWrapper::success($reponseData['Response']['SendStatusSet']);
        }
    }
}
